package com.jerry.boot.business.file;

import cn.hutool.core.io.FileUtil;
import com.jerry.boot.business.common.CommonService;
import com.jerry.boot.business.file.pojo.FileDto;
import com.jerry.boot.core.base.ApiException;
import com.jerry.boot.core.web.ServletContextHelper;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
@RequestMapping("/api/file")
public class FileController {

    @Resource
    private FileService fileService;

    @Resource
    private CommonService commonService;

    @RequestMapping("/{fileId}")
    public void file(@PathVariable("fileId") Long fileId) {
        FileDto fileDto = fileService.file(fileId);
        if (!FileUtil.exist(fileDto.getFilePath())) {
            throw new ApiException(104, fileId + "");
        }
        Long createUserId = fileDto.getCreateUserId();
        Long loginUserId = commonService.getLoginUser().getId();
        if (!loginUserId.equals(createUserId)) {
            throw new ApiException(105);
        }
        HttpServletResponse response = ServletContextHelper.getResponse();
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileDto.getFileName() + "\"");
        response.setHeader("Cache-Control", "no-cache");
        try (ServletOutputStream os = response.getOutputStream();
             FileInputStream fis = new FileInputStream(FileUtil.file(fileDto.getFilePath()))) {
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = fis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            os.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/upload")
    public FileDto upload(@RequestParam("file") MultipartFile file, @RequestParam(value = "avatar", required = false) boolean avatar) {
        FileDto fileDto = fileService.upload(file);
        if (avatar) {
            commonService.copyFile2AvatarFile(fileDto);
        }
        return fileDto;
    }

}
